package com.jsn.hello_cmake

import android.Manifest
import android.content.Context
import android.content.Intent
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Environment
import android.os.Environment.DIRECTORY_MUSIC
import android.os.PersistableBundle
import android.util.Log
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.jsn.hello_cmake.audio.AudioActivity
import com.jsn.sdklib.toast
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_audio_record.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception
import java.nio.ByteBuffer
import java.util.concurrent.atomic.AtomicBoolean

class AudioRecordActivity :AppCompatActivity() {


    val coroutineScope= CoroutineScope(Dispatchers.Main)
   // var fileh :File?=null

    val sample_rate=44100

    val channel_config=AudioFormat.CHANNEL_IN_MONO

    val audio_format=AudioFormat.ENCODING_PCM_16BIT

    val buffer_size_factor=2

    val buffer_size=AudioRecord.getMinBufferSize(sample_rate,channel_config,audio_format) *buffer_size_factor

    var inProgress:AtomicBoolean= AtomicBoolean(false)

    var mAudioRecord:AudioRecord?=null

     var context:Context?=null

     lateinit var startButton :Button

     lateinit var stopButton :Button

     lateinit var rxPermissions: RxPermissions

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_audio_record)


        jump_audio_track.setOnClickListener{
            startActivity(Intent(this,AudioActivity::class.java))
        }

        context=this

        rxPermissions=RxPermissions(this)

        startButton=findViewById(R.id.start)

        stopButton=findViewById(R.id.stop)

        startButton.setOnClickListener{

            rxPermissions.request(Manifest.permission.RECORD_AUDIO,Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe{
                    if(!it){
                        return@subscribe
                    }
                    else{
                        startRecord()
                        startButton.isEnabled=false
                        stopButton.isEnabled=true
                    }
                }


        }
        stopButton.setOnClickListener{
            stopRecord()
            startButton.isEnabled=true
            stopButton.isEnabled=false
        }
    }

    override fun onResume() {
        super.onResume()
        startButton.isEnabled=true
        stopButton.isEnabled=false

    }

    override fun onPause() {
        super.onPause()
        stopRecord()

    }

    fun stopRecord(){
        inProgress.set(false)
        mAudioRecord?.stop()
        mAudioRecord?.release()
        mAudioRecord=null

    }



    fun startRecord(){
        val file=File(Environment.getExternalStorageDirectory(),"recording.pcm")
        Log.e("filePath",file.absolutePath)
        mAudioRecord= AudioRecord(MediaRecorder.AudioSource.DEFAULT,sample_rate,channel_config,audio_format,buffer_size)
        mAudioRecord?.startRecording()
        context?.toast("start record")
        inProgress.set(true)
        coroutineScope.launch {
            withContext(Dispatchers.IO){ //切换到io线程
                val byteBuffer=ByteBuffer.allocateDirect(buffer_size)
                try {
                    val outStream=FileOutputStream(file)
                    while(inProgress.get()){
                        val result=mAudioRecord?.read(byteBuffer,buffer_size)
                        if(result!!<0) {
                            when (result) {
                                AudioRecord.ERROR, AudioRecord.ERROR_BAD_VALUE, AudioRecord.ERROR_DEAD_OBJECT -> {
                                    withContext(Dispatchers.Main) {
                                        context!!.toast("error" + result)
                                    }
                                }
                            }
                            return@withContext
                        }
                        outStream.write(byteBuffer.array(),0,buffer_size)
                        byteBuffer.clear()
                    }

                }catch (e:Exception){

                }
            }

        }
    }

}